package com.xpffly.assist.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

/**
 * @Author: xpengfei
 * @Date: 2020/12/19 20:27
 * @Description：获取网页信息的工具类
 */
public class GetWebPageInfoUtil {

    /**
     * 获取网页信息数据
     *
     * @param targetUrl 目标地址
     * @return 网页返回的数据
     * @throws IOException
     */
    public static String getPageInfo(String targetUrl) throws IOException {
        StringBuffer stringBuffer = new StringBuffer();
        BufferedReader bufferedReader = null;
        try {
            // 创建一个url对象，用于指定要采集信息的网址
            URL url = new URL(targetUrl);
            // 将读取到的字节转化为字符
            InputStreamReader inputStreamReader = new InputStreamReader(url.openStream(), "UTF-8");
            // 读取inputStreamReader中的字符
            bufferedReader = new BufferedReader(inputStreamReader);
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }
        return stringBuffer.toString();
    }
}
